import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Card, Tag, Row, Col } from 'antd';
import { NavLink } from 'react-router-dom';
import moment from 'moment';
import axios from '../../axios';
import './index.less';

const getColor = (type) => {
	const colors = ['magenta', 'volcano', 'orange', 'gold', 'lime', 'cyan', 'purple'];
	switch (type) {
	case 'coding':
		return 'blue';
	case 'life':
		return 'green';
	case 'cooking':
		return 'red';
	default:
		return colors[Math.floor(Math.random() * 6 + 1)];
	}
};

class ArticleList extends Component {
	UNSAFE_componentWillMount() {
		const { getArticleList } = this.props;
		getArticleList();
	}
	render() {
		const { articleList } = this.props;
		return (
			<Row className="article-list">
				<Col sm={24} xl={17} order={2} className="leftBox">
					{articleList && articleList.map((item, index) => (
						<NavLink to={`/index/articles/${item._id}`} key={index}>
							<Card className="article" hoverable>
								<h2>{item.title}</h2>
								<div className="info">
									<span>
										{item.tags.map(im => (
											<Tag key={im} color={getColor(im)}>{im}</Tag>
										))}
									</span>
									<span className="create-time">{moment(item.created_at).format('YYYY-MM-DD hh:mm:ss')}</span>
								</div>
							</Card>
						</NavLink>
					))}
				</Col>
				<Col sm={6} xl={6} offset={1} order={1} className="rightBox">loading...</Col>
			</Row>
		);
	}
}
ArticleList.propTypes = {
	articleList: PropTypes.array,
	getArticleList: PropTypes.func
};

const mapStateToProps = state => ({
	articleList: state.article.list
});
const mapDispatchToProps = dispath => ({
	getArticleList: () => {
		axios.get('https://api.justdodo.cn/acticles').then(res => {
			dispath({
				type: 'GET_ARTICLE_LIST',
				data: res.data.data.list
			});
		});
	}
});

export default connect(mapStateToProps, mapDispatchToProps)(ArticleList);